﻿//-----------------------------------------------------------------------
// <copyright file="ConsoleViewModel.Commands.cs" author="Artak Mkrtchyan">
//     Creative Commons - GNU General Public License (http://creativecommons.org/licenses/GPL/2.0/
// </copyright>
// <author>Artak Mkrtchyan</author>
// <email>mkArtak@gmail.com</email>
// <date>29/10/2012</date>
//-----------------------------------------------------------------------
using ConsoleHoster.ViewModel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleHoster.ViewModel
{
	public sealed partial class ConsoleViewModel
	{
		private IEnumerable<CommandDataViewModel> globalCommands;

		public IEnumerable<CommandDataViewModel> GlobalCommands
		{
			get
			{
				return this.globalCommands;
			}
			set
			{
				this.globalCommands = value;
				this.NotifyAvailableCommandsChange();
			}
		}

		public IDictionary<string, IList<CommandDataViewModel>> AvailableCommands
		{
			get
			{
				IEnumerable<CommandDataViewModel> tmpAllCommands = this.GlobalCommands ?? new List<CommandDataViewModel>();
				if (this.Project.Commands != null)
				{
					tmpAllCommands = tmpAllCommands.Concat(this.Project.Commands);
				}

				IDictionary<string, SortedList<string, CommandDataViewModel>> tmpResult = new Dictionary<string, SortedList<string, CommandDataViewModel>>();
				foreach (CommandDataViewModel tmpCommand in tmpAllCommands)
				{
					string tmpGroup = String.IsNullOrWhiteSpace(tmpCommand.GroupName) ? "Global Commands" : tmpCommand.GroupName;
					if (!tmpResult.ContainsKey(tmpGroup))
					{
						tmpResult[tmpGroup] = new SortedList<string, CommandDataViewModel>();
					}
					tmpResult[tmpGroup].Add(tmpCommand.Name, tmpCommand);
				}

				return tmpResult.OrderBy(item => item.Key).ToDictionary(item => item.Key, item => item.Value.Values);
			}
		}

		private void NotifyAvailableCommandsChange()
		{
			this.NotifyPropertyChange("AvailableCommands");
		}
	}
}
